module Holo
  class Holofile
    # 必选 属性
    REQUIRED_ATTRS ||= %i[name version git commit tag path branch].freeze
    attr_accessor(*REQUIRED_ATTRS)

    # 可选 属性
    OPTIONAL_ATTRS ||= %i[configurations modular_headers subspecs inhibit_warnings testspecs].freeze
    attr_accessor(*OPTIONAL_ATTRS)

    # 其他的属性
    attr_accessor :defined_in_file

    def initialize(defined_in_file = nil, &block)
      self.defined_in_file = defined_in_file
      if block
        instance_eval(&block)
      end
    end

    def self.from_file(path)
      puts "正在转换 #{path}:"

      # 1. 读取 每一个 xx.rb 文件的内容
      contents = File.open(path, 'r:utf-8', &:read)
      if contents.respond_to?(:encoding) && contents.encoding.name != 'UTF-8'
        contents.encode!('UTF-8')
      end
      if contents.tr!('“”‘’‛', %(""'''))
        # Changes have been made
        puts "Smart quotes were detected and ignored in your #{path.basename}. " \
                    'To avoid issues in the future, you should not use ' \
                    'TextEdit for editing it. If you are not using TextEdit, ' \
                    'you should turn off smart quotes in your editor of choice.'
      end
      puts contents

      # 2. 将 xx.rb 文件的内容, 转换成一个 ruby 类的 对象
      # rubocop:disable Lint/RescueException
      begin
        # rubocop:disable Eval
        eval(contents, nil, path.to_s)
        # rubocop:enable Eval
      rescue Exception => e
        raise "Invalid `#{path.basename}` file: #{e.message}"
      end
      # rubocop:enable Lint/RescueException
    end

    def inspect
      "<#{self.class}:#{object_id} name: #{name} version: #{version}>"
    end
  end
end